<?php
/**
 * Created by PhpStorm.
 * User: zd
 * Date: 2018/10/9
 * Time: 10:01
 */

namespace app\api\service;

use think\Loader;
use think\Request;

Loader::import('WorkWx.callback.WXBizMsgCrypt',EXTEND_PATH);
Loader::import('WorkWx.api.src.ServiceCorpAPI.',EXTEND_PATH,'.class.php');
class WorkBoss
{
    protected $encodingAesKey;
    protected $token;
    protected $corpId;
    private $suiteID;
    private $Secret;

    function __construct()
    {
        $this->encodingAesKey = config('boss.EncodingAESKey');
        $this->token = config('boss.Token');
        $this->suiteID = config('boss.SuiteID');
        $this->Secret = config('boss.Secret');
        $this->corpId = config('work.CorpID');
    }
    /**
     * 向企业微信返回通信标识
     * @return string
     */
    public function get(){
        $work = new Work($this->encodingAesKey, $this->token, $this->corpId);
        $sEchoStr =$work->get();
        return $sEchoStr;
    }
    /**
     * 处理微信返回的消息
     * @return mixed|string
     */
    public function getNotify(){
        $work = new Work($this->encodingAesKey, $this->token,$this->suiteID);
        $result = $work->getNotify();
        if (is_array($result)){
            return true;
        }else{
            return $result;
        }
    }
    /**
     * 获取预授权码
     * @return \ServiceCorpAPI
     */
    public function getPreAuthCode(){
        $work = new Work();
        $preAuthCode = $work->getPreAuthCode($this->suiteID,$this->Secret);
        return $preAuthCode;
    }
    /**
     *根据预授权码，获取永久授权码(测试)
     * @param $code
     * @return \GetPermanentCodeRsp
     */
    public function getTestPermanentCode($code){
        $work = new Work();
        $authInfo = $work->getPermanentCode($code,$this->suiteID,$this->Secret);
        return $authInfo;
    }
    /**
     *根据预授权码，获取永久授权码
     * @param $auth_code
     * @param $expires_in
     * @param $state
     * @return \GetPermanentCodeRsp
     */
    public function getPermanentCode($auth_code){
        $work = new Work();
        $authInfo = $work->getPermanentCode($auth_code,$this->suiteID,$this->Secret);
        return $authInfo;
    }
    /**
     * 设置应用配置信息
     */
    public function setAppConfig(){
        $work = new Work();
        $preAuthCode = $this->getPreAuthCode();
        $result =  $work->setAppConfig($preAuthCode,$this->suiteID,$this->Secret);
        return $result;
    }
    /**
     * 获取授权url
     * @return string
     */
    public function getAuthUrl($token){
        $work = new Work();
        $redirect_uri = urlencode('business.17jxyx.com/index/v1/boss/get_uri');
        $authUrl = $work->makeAuthUrl($this->suiteID,$this->Secret,$redirect_uri,$token);
        return $authUrl;
    }
    /**
     * 接收事件和消息
     * @param $CorpID
     * @return mixed|string
     */
    public function getEventInfo($CorpID){
        $getData = Request::instance()->param();
        $postData = file_get_contents('php://input');
        $sMsg = "";  // 解析之后的明文
        $wxcpt = new \WXBizMsgCrypt( $this->token,$this->encodingAesKey,$CorpID);
        $errCode =  $wxcpt->DecryptMsg($getData['msg_signature'],$getData['timestamp'],$getData['nonce'],$postData,$sMsg);
        if ($errCode == 0) {
            $data =Xml2Array($sMsg);
            $this->getInfoType($data);
            return $data;
        } else {
            return  "ERR: " . $errCode . "\n\n";
        }
    }
    /**
     * 获取用户信息
     * @param $code
     * @return mixed
     */
    public function getUserInfo($code){
        $work = new Work($this->encodingAesKey, $this->token,$this->suiteID);
        $suite_access_token = $work->getAccessToken($this->suiteID,$this->Secret);
        $url = "https://qyapi.weixin.qq.com/cgi-bin/service/getuserinfo3rd?access_token=".$suite_access_token."&code=".$code;
        $userInfo = curl_get($url);
        $data = json_decode($userInfo);
        if ($data->errcode == 0){
            return $data;
        }else{
            return false;
        }
    }

    /**
     * userId与openID互换
     * @param $userId
     * @return bool|mixed
     */
    public function userIdToOpenId($info,$userId){
        $work = new Work($this->encodingAesKey, $this->token,$this->suiteID);
        $suite_access_token = $work->getAccessToken($this->suiteID,$this->Secret);
        if (!cache($info->corpid)){
            $access_token = $work->get_access_token($suite_access_token,$info->permanent_code,$info->corpid);
        }else{
            $access_token = json_decode(cache($info->corpid));
        }
        $url = "https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_openid?access_token=".$access_token;
        $pagrams = ["userid"=>$userId];
        $result = curl_post($url,$pagrams);
        $data = json_decode($result);
        if ($data->errcode == 0){
            return $data;
        }else{
            return false;
        }
    }

    /**
     * 发送消息
     * @param $user_id
     * @return bool|mixed
     */
    public function deliveryMessage($user_id){
        $work = new Work($this->encodingAesKey, $this->token,$this->suiteID);
        $suite_access_token = $work->getAccessToken($this->suiteID,$this->Secret);
        $url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=".$suite_access_token;
        $pagrams = [];
        $result = curl_post($url,$pagrams);
        $data = json_decode($result);
        if ($data->errcode = 0){
            return $data;
        }else{
            return false;
        }
    }

    /**
     * 授权添加
     * @param $uid
     * @param $result
     * @param $type
     * @return $this
     */
    public function authorizeBoss($uid, $result,$type){
        $type['suitID'] = $this->suiteID;
        $info = \app\api\model\Work::creatWork($uid, $result,$type);
        return $info;
    }






    /**
     * 消息判断
     * @param $data
     */
    private function getInfoType($data){
        switch ($data['MsgType']){
            case 'text':
                break ;
            case 'image':
                break ;
            case 'voice':
                break ;
            case 'video':
                break ;
            case 'location':
                break ;
            case 'link':
                break ;
            case 'event':
                $this->getEvntType($data);
                break ;
        }
    }
    /**
     * 事件判断
     * @param $data
     * @return mixed
     */
    private function getEvntType($data){
        return $data;
    }


}